const Koa = require("koa");
const config = require("./config");
const path = require("path");
const router = require("./router/router");
const fs = require("fs");
const static = require("koa-static");
const start = require("./lib/index");
var nunjucks = require("koa-nunjucks-2");

const app = new Koa();
start()

// 配置模板引擎
app.use(nunjucks({
  ext: '',
  path: path.join(__dirname, './views'),// 指定视图目录
  nunjucksConfig: {   
    trimBlocks: true // 开启转义 防Xss
  }
}));

app.use(async function(ctx,next){
  let url = ctx.request.url
  if(url == "/" || url.indexOf(".html") != -1 && url != "/404.html"){
    let filename = url == "/"?"/index.html":url;
    filename = filename.substring(1,filename.length)
    let p = path.join(__dirname,"./views/") + filename;
    console.log("p",p)
    if(!fs.existsSync(p)){
      ctx.status = 302;
      ctx.redirect("/404.html")
    }
  }
  await next();
})

// allowedMethods()自动丰富response相应头，当未设置响应状态的时候自动设置
app.use(router.routes(),router.allowedMethods())

// 配置静态资源
app.use(static(path.join(__dirname,"./public/")))

app.listen(config.port,function(){
  console.log("run...")
})